package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bzkj.basicinfo.domain.ncc.NccBasicSkuType;
import com.bzkj.basicinfo.domain.ncc.NccBasicSkuTypeData;
import com.bzkj.basicinfo.mapper.NccBasicSkuTypeMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicSkuTypeService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.UniqueIdentifierGenerator;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.R;
import com.bzkj.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author wl
 * @description 针对表【ncc_basic_sku_type(NCC商品分类表)】的数据库操作Service实现
 * @createDate 2024-12-13 09:52:46
 * 物料分类：2
 */
@Slf4j
@Service("nccBasicSkuTypeServiceImpl")
public class NccBasicSkuTypeServiceImpl implements NccBasicSkuTypeService
{

    @Autowired
    private NccBasicSkuTypeMapper nccBasicSkuTypeMapper;

    @Autowired
    private UniqueIdentifierGenerator uniq;

    @Autowired
    private HttpClientUtils hcu;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    /**
     * 获取商品分类信息
     *
     * @Author wangzhichao
     * @Date 2024/12/13 10:32:17
     * @Param entity
     */
    @Override
    public List<NccBasicSkuType> findSkuTypeData(NccBasicSkuType entity)
    {
        return nccBasicSkuTypeMapper.findSkuTypeData(entity);
    }

    /**
     * 保存商品分类信息
     *
     * @Author wangzhichao
     * @Date 2024/12/13 10:32:57
     * @Param entity
     */
    @Override
    public AjaxResult saveSkuType(NccBasicSkuType entity)
    {
        NccBasicSkuType one = nccBasicSkuTypeMapper.getSkuTypeOne(entity.getNccStuCode());
        if(Objects.isNull(one)) {
            String key = "WMS" + uniq.generateUniqueIdentifier();
            String userName = SecurityUtils.getLoginUser().getUser().getUserName();
            entity.setCreator(userName);
            entity.setPkMarbasclass(key);
//            entity.setPkOrg("0001A1100000000021CH");
//            entity.setPkGroup("0001A1100000000021CH");
//            entity.setTstime(new Date());
            entity.setCreatetime(new Date());

            try {
                nccBasicSkuTypeMapper.saveSkuType(entity);
                return AjaxResult.success("新增成功");
            } catch(Exception e) {
                log.error("新增失败：{}", e);
                return AjaxResult.error("新增失败");
            }
        } else {
            return AjaxResult.error("分类代码重复");
        }
    }

    /**
     * 修改商品分类状态
     *
     * @Author wangzhichao
     * @Date 2024/12/13 10:33:18
     * @Param status
     * @Param pkMarbasclass
     */
    @Override
    public AjaxResult updateSkuTypeEnableStatus(String status, String pkMarbasclass)
    {
        try {
            int i = nccBasicSkuTypeMapper.updateSkuTypeEnableStatus(status, pkMarbasclass);
            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定数据");
        } catch(Exception e) {
            log.error("修改失败:{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 修改商品信息
     *
     * @Author wangzhichao
     * @Date 2024/12/13 10:33:33
     * @Param entity
     */
    @Override
    public AjaxResult updateSkuType(NccBasicSkuType entity)
    {
        NccBasicSkuType one = nccBasicSkuTypeMapper.getSkuTypeOne(entity.getNccStuCode());
        if(Objects.isNull(one)) {
            entity.setTstime(new Date());
            try {
                int i = nccBasicSkuTypeMapper.updateSkuType(entity);
                return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
            } catch(Exception e) {
                log.error("修改失败：{}", e);
                return AjaxResult.error("修改失败");
            }
        } else {
            if(entity.getPkMarbasclass().equals(one.getPkMarbasclass())) {
                nccBasicSkuTypeMapper.updateSkuType(entity);
                return AjaxResult.success("修改成功");
            } else {
                return AjaxResult.error("分类代码重复");
            }
        }
    }

    @Override
    public R findNccBasicSkuTypeAll()
    {
        List<NccBasicSkuType> skuTypeAll = nccBasicSkuTypeMapper.getSkuTypeAll();
        return R.ok(skuTypeAll);
    }

    @Override
    public List<String> findNccBasicSkuTypeNameList(String name)
    {
        return nccBasicSkuTypeMapper.findNccBasicSkuTypeNameList(name);
    }

    @Override
    public AjaxResult jobMethodExecute(Boolean flag)
    {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 2, pkOrgCode);
        String responseBody = response.body();
        JSONObject entries = JSONUtil.parseObj(responseBody);
        JSONArray dataArray = entries.getJSONArray("data");
        List<NccBasicSkuTypeData> skuTypeDataList = dataArray.toList(NccBasicSkuTypeData.class);

        if(! skuTypeDataList.isEmpty())
            extracted(skuTypeDataList);

        return AjaxResult.success("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<NccBasicSkuTypeData> list)
    {
        for (NccBasicSkuTypeData nccBasicSkuTypeData : list) {
            nccBasicSkuTypeMapper.insertOrUpdate(nccBasicSkuTypeData);
        }
    }

    @Override
    public AjaxResult deleteBasicSkuTypeById(String id) {
        int i = nccBasicSkuTypeMapper.deleteById(id);
        if(i > 0){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败");
        }
    }
}




